/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.pokemon.web;

import com.pokemon.dto.BadgeDTO;
import com.pokemon.dto.StadiumDTO;
import com.pokemon.dto.TrainerDTO;
import com.pokemon.services.BadgeService;
import com.pokemon.services.StadiumService;
import com.pokemon.services.TrainerService;
import com.pokemon.web.security.CustomUserDetails;
import com.pokemon.web.wrapper.TrainerDTOWrapper;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import net.sourceforge.stripes.action.Before;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.LocalizableError;
import net.sourceforge.stripes.validation.ValidationErrors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
 
@UrlBinding("/badges/{$event}")
public class BadgeActionBean extends CustomActionBean {
 
    final static Logger log = LoggerFactory.getLogger(BadgeActionBean.class);
 
    @SpringBean
    protected BadgeService badgeManager;
    @SpringBean
    protected TrainerService trainerManager;
    @SpringBean
    protected StadiumService stadiumManager;
 
    @DefaultHandler
    public Resolution all() {
        log.debug("all()");
        return new ForwardResolution("/badge/badge.jsp");
    }
 
    public List<BadgeDTO> getBadges() {
        return badgeManager.getAllBadges();
    }
    
    private List<TrainerDTO> trainers = new ArrayList<TrainerDTO>();
    private List<TrainerDTOWrapper> trainers1 = new ArrayList<TrainerDTOWrapper>();
     
    private TrainerDTO user;
    
    public TrainerDTO getCurrentTrainer() {
        CustomUserDetails loggedUser = (CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return loggedUser.getTrainer();
    }
    
    /*public List<TrainerDTOWrapper> getTrainer(){
        trainers1.clear();
        TrainerDTO trainer = trainerManager.getTrainer(user.getId());
        TrainerDTOWrapper trainerWrapper = new TrainerDTOWrapper();
        trainerWrapper.setId(trainer.getId());
        trainerWrapper.setFullName(user.getFirstName() + " " + user.getLastName());
        System.out.println(trainerWrapper.getFullName());
        trainers1.add(trainerWrapper);
        return trainers1;
    }*/
    
    public List<TrainerDTOWrapper> getAllTrainersWithoutCurrent(){
        user = this.getCurrentTrainer();
        trainers = trainerManager.getAllTrainers();
        trainers1.clear();
        TrainerDTO currentTrainer = trainerManager.getTrainer(user.getId());
        for (TrainerDTO t : trainers){
            if(currentTrainer.equals(t)) {
                continue;
            }
            TrainerDTOWrapper trainer = new TrainerDTOWrapper();
            
            trainer.setId(t.getId());
            trainer.setFullName(t.getFirstName() + " " + t.getLastName());
            System.out.println(trainer.getFullName());
            trainers1.add(trainer);
        }
        return trainers1;
    }
    
    public List<TrainerDTOWrapper> getAllTrainers(){
        trainers = trainerManager.getAllTrainers();
        trainers1.clear();
        for (TrainerDTO t : trainers){
            TrainerDTOWrapper trainer = new TrainerDTOWrapper();
            
            trainer.setId(t.getId());
            trainer.setFullName(t.getFirstName() + " " + t.getLastName());
            System.out.println(trainer.getFullName());
            trainers1.add(trainer);
        }
        return trainers1;
    }
    
    private List<StadiumDTO> stadiums = new ArrayList<StadiumDTO>();
    
    public List<StadiumDTO> getAllStadiums(){
        stadiums = stadiumManager.getAllStadiums();
        List<StadiumDTO> resultList = new ArrayList<StadiumDTO>();
        Iterator<StadiumDTO> iterator = stadiums.iterator();
        StadiumDTO stadium;
	while (iterator.hasNext()) {
            stadium = iterator.next();
		if (stadium.getTrainer() != null)
                    resultList.add(stadium);
	}
        return resultList;
    }
    
    public List<StadiumDTO> getMyStadium(){
        user = this.getCurrentTrainer();
        stadiums = stadiumManager.getAllStadiums();
        List<StadiumDTO> resultList = new ArrayList<StadiumDTO>();
        Iterator<StadiumDTO> iterator = stadiums.iterator();
        StadiumDTO stadium;
	while (iterator.hasNext()) {
            stadium = iterator.next();
		if (stadium.getTrainer().equals(user))
                    resultList.add(stadium);
	}
        return resultList;
    }
    
    private BadgeDTO badge;
 
    public Resolution add() {
        log.debug("add() badge={}", badge);
        try{
        badgeManager.addBadge(badge);
        } 
        
        catch (NullPointerException ex){
            ValidationErrors errors = new ValidationErrors();
            errors.addGlobalError( new LocalizableError("StadiumTrainerNull") );
            getContext().setValidationErrors(errors);
            return getContext().getSourcePageResolution();
        }
        catch (Exception ex){
            ValidationErrors errors = new ValidationErrors();
            errors.addGlobalError( new LocalizableError("BadBadgeInput") );
            getContext().setValidationErrors(errors);
            return getContext().getSourcePageResolution();
        }
        return new RedirectResolution(this.getClass(), "all");
    }
 
    public BadgeDTO getBadge() {
        return badge;
    }
 
    public void setBadge(BadgeDTO badge) {
        this.badge = badge;
    }
    
    public Resolution delete() {
        log.debug("delete({})", badge.getId());
        badgeManager.removeBadge(badge);
        return new RedirectResolution(this.getClass(), "all");
    }
    
    @Before(stages = LifecycleStage.BindingAndValidation, on = {"edit", "save"})
    public void loadPokemonFromDatabase() {
        String ids = getContext().getRequest().getParameter("badge.id");
        if (ids == null) return;
        badge = badgeManager.getBadge(Long.parseLong(ids));
    }
 
    public Resolution edit() {
        log.debug("edit() badge={}", badge);
        return new ForwardResolution("/badge/edit.jsp");
    }
 
    public Resolution save() {
        log.debug("save() badge={}", badge);
        try {
        badgeManager.updateBadge(badge); 
        }
        catch (NullPointerException ex){
            ValidationErrors errors = new ValidationErrors();
            errors.addGlobalError( new LocalizableError("StadiumTrainerNull") );
            getContext().setValidationErrors(errors);
            return getContext().getSourcePageResolution();
        }
        catch (Exception ex){
            ValidationErrors errors = new ValidationErrors();
            errors.addGlobalError( new LocalizableError("BadBadgeInput") );
            getContext().setValidationErrors(errors);
            return getContext().getSourcePageResolution();
        }
        return new RedirectResolution(this.getClass(), "all");
    }
    
    public Resolution cancel() {
        return new RedirectResolution(this.getClass(), "all");
    }
}